package com.tan.controller.admin;

import com.tan.domain.response.Result;
import com.tan.domain.response.StatusCode;
import org.apache.commons.io.FileUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @description:
 * @author: longshifu
 * @time: 2022/7/20 20:01
 */
@RestController
public class PictureController {

    @PostMapping(value = "/upload")
    public Result uploadFast(@RequestParam("file") MultipartFile file) {
        try {
            // 文件拓展名
            String extName = file.getOriginalFilename().split("\\.")[1];
            ClientGlobal.initByProperties("fastdfs-client.properties");
            byte[] bytes = file.getBytes();
            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer = null;
            StorageClient1 client1 = new StorageClient1(trackerServer, storageServer);
            String fileId2 = client1.upload_file1(bytes, extName, null);
            System.out.println(fileId2);
            return new Result(true, StatusCode.ERROR,"上传图片成功",fileId2);
        } catch (IOException | MyException e) {
            e.printStackTrace();
            return new Result(true, StatusCode.ERROR,"保存图片异常",null);
        }
    }

    /**
     * 这个方法可以上传到本地  因为已经配置云服务器了，就不保存在本地了
     * @param file
     * @return
     */
    @PostMapping(value = "/uploadLocal")
    public Result upload2(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new Result(true, StatusCode.ERROR,"上传图片为空",null);
        }
        if (file.getSize() > 1024 * 1024 * 10) {
            return new Result(true, StatusCode.ERROR,"图片大小不能大于10M",null);
        }
        //获取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        // 保存的本地地址
        String savePath = "F:\\Desktop\\blog\\image\\";
        File savePathFile = new File(savePath);
        if (!savePathFile.exists()) {
            savePathFile.mkdir();
        }
        String fileName = UUID.randomUUID().toString().replace("-", "") + "." + suffix;
        System.out.println(fileName);
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(savePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(true, StatusCode.ERROR,"保存图片异常",null);
        }
        return new Result(true, StatusCode.ERROR,"上传图片成功",fileName);
    }



}
